﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace KDSugar.Galaxy.API.Push
{
    /// <summary>
    /// 单据下推指令
    /// </summary>
    public class PushCommand : Base.BaseNumberIdEntry
    {
        /// <summary>
        /// 单据下推指令URL
        /// </summary>
        public const string PUSH_COMMAND_URL = "/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc";

        /// <summary>
        /// 初始化单据下推指令
        /// </summary>
        /// <param name="_formId">源单FormId</param>
        /// <param name="_client"></param>
        public PushCommand(string _formId,GalaxyCloudAPIClient _client)
            : base(PUSH_COMMAND_URL, _formId,_client)
        {

        }

        /// <summary>
        /// 验证单据下推执行返回是否符合规则
        /// </summary>
        /// <param name="_responseData"></param>
        /// <returns></returns>
        public override bool ValidateResponseDataRule(string _responseData)
        {
            //bool result = false;
            //if (!string.IsNullOrWhiteSpace(_responseData))
            //{
            //    try
            //    {
            //        Base.Result.BaseReturnInfo resultInfo = JsonConvert.DeserializeObject<Base.Result.BaseReturnInfo>(_responseData);
            //        if (resultInfo.Result != null)
            //        {
            //            result = true;
            //        }
            //    }
            //    catch
            //    {
            //        result = false;
            //    }
            //}
            //return result;
            return true;
        }

        /// <summary>
        /// 构建单据下推请求内容
        /// </summary>
        /// <returns></returns>
        public override string BuildRequestContent()
        {
            //return BuildRequestContentByAppendFormId();
            string result = null;
            List<object> para = new List<object>();
            para.Add(GetFormId());
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("Ids", !string.IsNullOrWhiteSpace(Ids) ? Ids : "");
            dic.Add("Numbers", Numbers != null ? Numbers : new List<string>());
            dic.Add("EntryIds", !string.IsNullOrWhiteSpace(EntryIds) ? EntryIds : "");
            dic.Add("RuleId", !string.IsNullOrWhiteSpace(RuleId) ? RuleId : "");
            dic.Add("TargetBillTypeId", !string.IsNullOrWhiteSpace(TargetBillTypeId) ? TargetBillTypeId : "");
            if (TargetOrgId > 0)
            {
                dic.Add("TargetOrgId", TargetOrgId);
            }
            dic.Add("TargetFormId", !string.IsNullOrWhiteSpace(TargetFormId) ? TargetFormId : "");
            dic.Add("IsEnableDefaultRule", IsEnableDefaultRule);
            dic.Add("IsDraftWhenSaveFail", IsDraftWhenSaveFail);
            dic.Add("CustomParams", CustomParams);
            para.Add(JsonConvert.SerializeObject(dic));
            result = JsonConvert.SerializeObject(para);
            return result;
        }

        /// <summary>
        /// 转换规则内码
        /// <para>未启用默认转换规则时，则必录</para>
        /// </summary>
        public string RuleId { get; set; }

        /// <summary>
        /// 目标单据类型内码
        /// </summary>
        public string TargetBillTypeId { get; set; }

        /// <summary>
        /// 目标组织内码
        /// <para>【注意】单组织/标准版|请勿赋值</para>
        /// </summary>
        public long TargetOrgId { get; set; }

        /// <summary>
        /// 目标单据FormId
        /// <para>启用默认转换规则时，则必录</para>
        /// </summary>
        public string TargetFormId { get; set; }

        /// <summary>
        /// 是否启用默认转换规则，默认false
        /// </summary>
        public bool IsEnableDefaultRule { get; set; } = false;

        /// <summary>
        /// 保存失败时是否暂存，默认false
        /// <para>注意：暂存的单据是没有编码的</para>
        /// </summary>
        public bool IsDraftWhenSaveFail { get; set; } = false;

        /// <summary>
        /// 自定义参数，字典类型，格式："{key1:value1,key2:value2,...}"
        /// <para>注：传到转换插件的操作选项中，平台不会解析里面的值</para>
        /// </summary>
        public Dictionary<string, object> CustomParams { get; set; }

        /// <summary>
        /// 执行下推单据操作
        /// </summary>
        public Base.Result.ResponseStatusInfo ExecutePushBill()
        {
            Base.Result.ResponseStatusInfo result = null;
            var resultPack = APIClient.ExecuteCommand(this);
            if (resultPack != null)
            {
                string errorMsg = "未知错误";
                try
                {
                    if (ValidateResponseDataRule(resultPack.ResponseData))
                    {
                        errorMsg = "返回数据JSON反序列化为对象失败";
                        Base.Result.BaseReturnInfo returnInfo = JsonConvert.DeserializeObject<Base.Result.BaseReturnInfo>(resultPack.ResponseData);
                        if (returnInfo != null)
                        {
                            var resultInfo = returnInfo.Result;
                            if (resultInfo != null)
                            {
                                result = resultInfo.ResponseStatus;
                                if (result == null)
                                {
                                    errorMsg = "ResponseStatus为NULL";
                                    throw new Exception(errorMsg);
                                }
                            }
                            else
                            {
                                errorMsg = "Result为NULL";
                                throw new Exception(errorMsg);
                            }
                        }
                        else
                        {
                            errorMsg = "反序列化为对象后对象为NULL";
                            throw new Exception(errorMsg);
                        }
                    }
                    else
                    {
                        errorMsg = "返回数据规则验证失败";
                        throw new Exception(errorMsg);
                    }
                }
                catch(Except.ExecuteException ex)
                {
                    ex.OperateCommandName = GetOperateCommandName();
                    ex.AppendMessage = errorMsg;
                    ex.ExecuteData = resultPack;
                    throw ex;
                }
            }
            else
            {
                //未获取到返回
                throw new Exception(Constant.GetExecuteReturnNullErrorStr("下推"));
            }
            return result;
        }
    }
}
